package com.kaishengit.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaishengit.entity.Project;
import com.kaishengit.entity.ProjectEmployee;
import com.kaishengit.service.ProjectService;
import com.kaishengit.service.ProjectEmployeeService;

public class NewPojectAdd extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			doPost(request,response);
	
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		request.setCharacterEncoding("UTF-8");
		String projectname = request.getParameter("projectname");
		
		ProjectService projectService = new ProjectService();
		
		Project project1 = projectService.findByName(projectname);
		
		if(project1==null) {
			String projectdesc = request.getParameter("projectdesc");
			
			
			String manager = request.getParameter("manager");
			
			String[] workers = request.getParameterValues("worker");
			
			System.out.println(workers);
			
			
			
			Project project = new Project();
			
			ProjectEmployee projectEmployee = new ProjectEmployee();
			ProjectEmployeeService projectEmployeeService = new ProjectEmployeeService();
			
			UUID uuid = UUID.randomUUID();
			
			projectEmployee.setEmployid(manager);
			projectEmployee.setProjectid(uuid.toString());
			projectEmployee.setManager(true);
			
			
			for(int i=0;i<workers.length;i++) {
				ProjectEmployee projectEmployeeworker = new ProjectEmployee();
				projectEmployeeworker.setEmployid(workers[i]);
				projectEmployeeworker.setProjectid(uuid.toString());
				projectEmployeeworker.setManager(false);
				
				projectEmployeeService.save(projectEmployeeworker);
				
			}
			
			
			
			project.setId(uuid.toString());
			project.setName(projectname);
			project.setDesc(projectdesc);
			project.setCreatetime(DateUtil.getNow());
			
			
		
			projectEmployeeService.save(projectEmployee);
			
			projectService.save(project);
			
			response.sendRedirect("projectlistview.jspx");
		}else {
			response.sendRedirect("newproject.jspx?state=10002");
		}

	
	}

	
	public void init() throws ServletException {
		// Put your code here
	}

}
